package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type content struct {
	iContent store.IContent
}

var Content = &content{
	iContent: postgres.Content,
}

func (a *content) init() func() {
	return func() {}
}

func (a *content) onEvent(*event.Data) {}

// Create 创建
func (a *content) Create(ctx context.Context, in *model.ContentCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildContent(in)
	_, err = a.iContent.Create(ctx, c)
	return err
}

// Update 更新
func (a *content) Update(ctx context.Context, in *model.ContentUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.EbikeTypeId != nil {
		dict["ebike_type_id"] = in.EbikeTypeId
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.Kind != nil {
		dict["kind"] = in.Kind
	}

	if in.Title != nil {
		dict["title"] = in.Title
	}

	if in.Content != nil {
		dict["content"] = in.Content
	}

	if in.Country != nil {
		dict["country"] = in.Country
	}

	if in.Language != nil {
		dict["language"] = in.Language
	}

	if in.Url != nil {
		dict["url"] = in.Url
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iContent.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *content) Delete(ctx context.Context, in *model.ContentDeleteRequest) error {
	return a.iContent.Delete(ctx, in.Id)
}

// List 列表查询
func (a *content) List(ctx context.Context, in *model.ContentListRequest) (*model.ContentListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Content
		out   = &model.ContentListResponse{}
	)

	if total, list, err = a.iContent.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.ContentsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *content) Find(ctx context.Context, in *model.ContentInfoRequest) (*model.ContentInfo, error) {
	var (
		err  error
		data *entity.Content
		out  = &model.ContentInfo{}
	)

	if data, err = a.iContent.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.ContentEntityToDto(data)
	return out, nil
}

// buildContent 构建创建数据现场
func buildContent(in *model.ContentCreateRequest) *entity.Content {
	// todo: check the entity is required
	return &entity.Content{

		EbikeTypeId: in.EbikeTypeId,

		Type: in.Type,

		Kind: in.Kind,

		Title: in.Title,

		Content: in.Content,

		Country: in.Country,

		Language: in.Language,

		Url: in.Url,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
